<?php

namespace controller;

/**
 * Bazowa klasa dla sklepu
 *
 * @author Damian
 */
class Shop extends Controller {

    public $perPage = 12;

    /**
     * <p>aktualna kategoria</p>
     * @var \model\TblCategory 
     */
    protected $category;

    /**
     * <p>główna kategoria w sklepie</p>
     * @var \model\TblCategory 
     */
    protected $mainCategory;
    /**
     *
     * @var \model\TblCustomer
     */
    protected $Customer = null;
    
    /**
     * 
     * @param type $options
     * @throws exceptions\CategoryNotFoundException
     */
    public function __construct($options = array()) {
       
        $session = \library\Registry::get("session");
        $this->Customer = $session->get("customer");
        $this->defaultLayout = "layout/shop";
        parent::__construct($options);
        $shopCategoryURL = (\library\RequestMethods::get("categoryURL") == null) ? "kategoria_glowna" : \library\RequestMethods::get("categoryURL");
        $this->category = \model\TblCategory::getModel()->getByURL($shopCategoryURL, $this->shop->ShopID);
        if (!$this->category) {
            throw new exceptions\CategoryNotFoundException("kategoria " . \library\RequestMethods::get("categoryURL") . " nie została odnaleziona");
        }
        
        //pobranie kategorii głównej
        if ($shopCategoryURL == "kategoria_glowna") {
            $this->mainCategory = $this->category;
        } else {
            //pobranie głównej kategorii
            $this->mainCategory = \model\TblCategory::getModel()->getByURL("kategoria_glowna", $this->shop->ShopID);
        }
        if ($this->category->HasChildren == 1) {
            $childrenMain = $this->category->getChildren();
        } 
        elseif ($this->category->ParentCategoryID==null && $this->category->HasChildren == 0){
            $childrenMain=array();
        }
        
        else {
            $parentCriteria = new \model\Criteria();
            $parentCriteria->from(\model\TblCategory::getModel()->getTable())->where(\model\TblCategory::PARENT_CATEGORY_ID, "=", $this->category->ParentCategoryID);
            $childrenMain = \model\TblCategory::getModel()->first($parentCriteria)->getChildren();
        }
        
        foreach ($childrenMain as &$cat) {
            $IDs = $cat->getAllIds();
            $cat->ItemCount = \model\TblProduct::getModel()->createCriteria($this->shop->ShopID)
                            ->in(\model\TblProduct::CATEGORY_ID, $IDs, \model\TblCategory::getModel()->getTable(), " and ")
                            ->where(\model\TblProduct::ACTIVE, "=", 1, \model\TblProduct::getModel()->getTable(), " and ")->count();
        }

        $manufacturers = \model\TblManufacturer::getModel()->getAllByShopID($this->shop->ShopID);
        $manufacturerURL = \library\RequestMethods::get("manufacturerURL");
        foreach ($manufacturers as &$man) {
            $man->itemCount = \model\TblProduct::getModel()->createCriteria($this->shop->ShopID)
                            ->where(\model\TblProduct::MANUFACTURER_ID, "=", $man->ManufacturerID, \model\TblManufacturer::getModel()->getTable(), " and ")
                            ->where(\model\TblProduct::ACTIVE, "=", 1, \model\TblProduct::getModel()->getTable(), " and ")->count();
        }
        //pobranie koszyka
        $basket = ($session->get("basket")) ? $session->get("basket") : new \library\Basket();
        $view = $this->getLayoutView();
        $layoutView = $this->getLayoutView();
        $layoutView->set("basket", $basket);
        $layoutView->set("customer", $this->Customer);
        $view->set("MainCategoryList", $childrenMain);
        $view->set("category", $this->category);
        $list = $this->category->createBreadCramps();
        $view->set("manufacturerURL", $manufacturerURL);
        $view->set("CategoryListUP", $list);
        $view->set("manufacturers", $manufacturers);
        if ($this->Customer) {
            $this->perPage = $this->Customer->ProductsPerPage;
            $conversationsCriteria = new \model\Criteria();
            $conversationsCriteria->from(\model\TblConversation::getModel()->getTable())
                    ->where(\model\TblConversation::CUSTOMER_ID, "=", $this->Customer->CustomerID);
            $Conversations = \model\TblConversation::getModel()->all($conversationsCriteria);
            if ($Conversations) {
                $unread = 0;
                foreach ($Conversations as $conv) {
                    $messageCountCriteria = new \model\Criteria();
                    $messageCountCriteria->from(\model\TblAnswer::getModel()->getTable())
                            ->where(\model\TblAnswer::CONVERSATION_ID, "=", $conv->ConversationID)
                            ->where(\model\TblAnswer::SEND_BY_CUSTOMER, "=", 0, false, " and ")
                            ->where(\model\TblAnswer::SEEN, "=", 0, false, " and ");
                    $unread+= $messageCountCriteria->count();
                }
                $layoutView->set("unread", $unread);
            }
            $layoutView->set("customer",$this->Customer);
        }
        $seller = $session->get("seller");
        if ($seller){
            $shopCriteria = new \model\Criteria();
            $shopCriteria->from(\model\TblShop::getModel()->getTable())
                    ->join(\model\TblShop::getModel())
                    ->join(\model\TblShopSeller::getModel())
                    ->where(\model\TblShopSeller::SELLER_ID, "=", $seller->SellerID,  \model\TblShopSeller::getModel()->getTable());
            $shop = \model\TblShopSeller::getModel()->first($shopCriteria);
            $url = "/".$shop->ShopID->URL."/seller";
            $layoutView->set("adminURL",$url);
        }
        
    }

    public function index() {
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "Witamy na stronie głównej sklepu " . $this->shop->Name);
        $NewProductsCriteria = \model\TblProduct::getModel()->createCriteria($this->shop->ShopID);
        $NewProductsCriteria->limit(3)->order(\model\TblProduct::ADDITION_DATE, " desc ");
        $newProductsData = new \model\DataTable(\model\TblProduct::getModel()->all($NewProductsCriteria));
        $newProducts= $newProductsData->getModelData(true);
        $view = $this->getActionView();
        $view->set("newProducts",$newProducts);
        
        $BoughtProductsListCriteria = new \model\Criteria();
        $BoughtProductsListCriteria->from(\model\TblProductOrder::getModel()->getTable(),["Distinct(`tblproductorder`.`ProductID`)"=>"ProductID"])
                ->join(\model\TblOrder::getModel(),array())
                ->limit(3)->order(\model\TblOrder::ORDER_DATE, " desc ");        
        $BoughtProductsList = $BoughtProductsListCriteria->all();
        $listID = [];
        //var_dump($BoughtProductsListCriteria->getSelectQuery());
        foreach ($BoughtProductsList as $product){
            $listID[]=$product["tblorder"]["ProductID"];
        }
        $BoughtProductsCriteria = \model\TblProduct::getModel()->createCriteria($this->shop->ShopID);
        $BoughtProductsCriteria->in(\model\TblProduct::ID, $listID,  \model\TblProduct::getModel()->getTable(), " and ");
        $BoughtProductsData = new \model\DataTable(\model\TblProduct::getModel()->all($BoughtProductsCriteria));
        $BoughtProducts = $BoughtProductsData->getModelData(true);
        $view->set("BoughtProducts",$BoughtProducts);
        $lastWatchListCriteria = new \model\Criteria();
        $lastWatchList=$lastWatchListCriteria->from(\model\TblLogWatch::getModel()->getTable(),["Distinct(`tbllogwatch`.`ProductID`)"=>"ProductID"])
                ->limit(3)->order(\model\TblLogWatch::WATCH_DATE," desc ")->all();
        $watchList = array();
        foreach ($lastWatchList as $product){
            $watchList[]=$product[\model\TblLogWatch::PRODUCT_ID];
        }
        $watchListCriteria = \model\TblProduct::getModel()->createCriteria($this->shop->ShopID);
        $watchListCriteria->in(\model\TblProduct::ID, $watchList,  \model\TblProduct::getModel()->getTable(), " and ")
                ->join(\model\TblLogWatch::getModel())
                ->order(\model\TblLogWatch::WATCH_DATE," desc ")->all();
        $watchListData = new \model\DataTable(\model\TblProduct::getModel()->all($watchListCriteria));
        $watchListProducts =  $watchListData->getModelData(true);
        $view->set("watchListProducts",$watchListProducts);
        $this->render();
    }
    public function lastBought(){
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "ostatnio kupione produtkty ");
        $BoughtProductsListCriteria = new \model\Criteria();
        $BoughtProductsListCriteria->from(\model\TblProductOrder::getModel()->getTable(),["Distinct(`tblproductorder`.`ProductID`)"=>"ProductID"])
                ->join(\model\TblOrder::getModel(),array())
                ->limit(9)->order(\model\TblOrder::ORDER_DATE, " desc ");        
        $BoughtProductsList = $BoughtProductsListCriteria->all();
        $view = $this->getActionView();
        $listID = [];
        //var_dump($BoughtProductsListCriteria->getSelectQuery());
        foreach ($BoughtProductsList as $product){
            $listID[]=$product["tblorder"]["ProductID"];
        }
        $BoughtProductsCriteria = \model\TblProduct::getModel()->createCriteria($this->shop->ShopID);
        $BoughtProductsCriteria->in(\model\TblProduct::ID, $listID,  \model\TblProduct::getModel()->getTable(), " and ");
        $BoughtProductsData = new \model\DataTable(\model\TblProduct::getModel()->all($BoughtProductsCriteria));
        $BoughtProducts = $BoughtProductsData->getModelData(true);
        $view->set("BoughtProducts",$BoughtProducts);
        $this->render();
    }
    public function lastSeen(){
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "ostatnio oglądane produtkty ");
        $lastWatchListCriteria = new \model\Criteria();
        $view = $this->getActionView();
        $lastWatchList=$lastWatchListCriteria->from(\model\TblLogWatch::getModel()->getTable(),["Distinct(`tbllogwatch`.`ProductID`)"=>"ProductID"])
                ->limit(3)->order(\model\TblLogWatch::WATCH_DATE," desc ")->all();
        $watchList = array();
        foreach ($lastWatchList as $product){
            $watchList[]=$product[\model\TblLogWatch::PRODUCT_ID];
        }
        $watchListCriteria = \model\TblProduct::getModel()->createCriteria($this->shop->ShopID);
        $watchListCriteria->in(\model\TblProduct::ID, $watchList,  \model\TblProduct::getModel()->getTable(), " and ")
                ->join(\model\TblLogWatch::getModel())
                ->order(\model\TblLogWatch::WATCH_DATE," desc ")->all();
        $watchListData = new \model\DataTable(\model\TblProduct::getModel()->all($watchListCriteria));
        $watchListProducts =  $watchListData->getModelData(true);
        $view->set("watchListProducts",$watchListProducts);
        $this->render();
    }
    public function lastAdd(){
        $layoutView = $this->getLayoutView();
        $layoutView->set("paneltitle", "Ostatnio dodane produkty " );
        $NewProductsCriteria = \model\TblProduct::getModel()->createCriteria($this->shop->ShopID);
        $NewProductsCriteria->limit(9)->order(\model\TblProduct::ADDITION_DATE, " desc ");
        $newProductsData = new \model\DataTable(\model\TblProduct::getModel()->all($NewProductsCriteria));
        $newProducts= $newProductsData->getModelData(true);
        $view = $this->getActionView();
        $view->set("newProducts",$newProducts);
        $this->render();
    }

}
